package com.peak.spring.boot.core.web;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import com.peak.spring.boot.api.web.JsonList;
import com.peak.spring.boot.api.web.JsonMessage;
import com.peak.spring.boot.api.web.JsonPage;
import com.peak.spring.boot.core.mapper.BeanMapper;
import com.peak.spring.boot.tools.Emptys;

public class MappingJackson2Converter extends MappingJackson2HttpMessageConverter {

	@Override
	protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {
		if (object instanceof JsonPage) {
			JsonPage json = (JsonPage) object;
			List<?> rows = json.getRows();
			if (Emptys.isNotEmpty(rows) && Emptys.isNotEmpty(json.getTargetClass())) {
				List<Map<String, Object>> mapList = BeanMapper.mapList(rows, json.getTargetClass());
				json.getRows().clear();
				json.getRows().addAll(mapList);
			}
		} else if (object instanceof JsonList) {
			JsonList json = (JsonList) object;
			List<?> rows = json.getRows();
			if (Emptys.isNotEmpty(rows) && Emptys.isNotEmpty(json.getTargetClass())) {
				List<Map<String, Object>> mapList = BeanMapper.mapList(rows, json.getTargetClass());
				json.getRows().clear();
				json.getRows().addAll(mapList);
			}
		} else if (object instanceof JsonMessage) {
			JsonMessage json = (JsonMessage) object;
			if (json.getTargetClass() != null) {
				Object message = BeanMapper.map(json.getMessage(), json.getTargetClass());
				json.setMessage(message);
			}
		}
		super.writeInternal(object, type, outputMessage);
	}
}
